package top.deepdesigner.service.Impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;
import top.deepdesigner.pojo.DtsTopic;
import top.deepdesigner.service.DtsTopicService;

import java.util.Date;
import java.util.List;

/**
 * Start up <br/>
 * Created with IntelliJ IDEA. <br/>
 * Project Name: shop_manage <br/>
 * Author: duanruiqing <br/>
 * DateTime: 2022/9/21 星期三 22:23:23 <br/>
 */
@Service
public class DtsTopicServiceImpl extends ServiceImpl<BaseMapper<DtsTopic>, DtsTopic> implements DtsTopicService {

  @Override
  public Long getTopicCount() {
    return this.count(new LambdaQueryWrapper<DtsTopic>().eq(true, DtsTopic::getDeleted, 0));

  }

  @Override
  public List<DtsTopic> getTopicList(Integer page, Integer limit, String sort, String order, String title, String subtitle) {
    QueryWrapper<DtsTopic> wrapper = new QueryWrapper<>();
    wrapper.eq(true, "deleted", 0)
        .like(!StringUtils.isEmpty(title), "title", title)
        .like(!StringUtils.isEmpty(subtitle), "subtitle", subtitle)
        .orderBy(!StringUtils.isEmpty(sort), "asc".equalsIgnoreCase(order), sort);
    return this.page(new Page<>(page, limit), wrapper).getRecords();
  }

  @Override
  @Transactional
  public DtsTopic createTopic(DtsTopic topic) {
    List<DtsTopic> list = this.list(new LambdaQueryWrapper<DtsTopic>()
        .eq(DtsTopic::getId, topic.getId())
        .eq(DtsTopic::getDeleted, 0));
    if (list != null && list.size() == 0) {
      this.save(topic);
      return topic;
    }
    return null;
  }

  @Override
  @Transactional
  public DtsTopic updateTopic(DtsTopic topic) {
    topic.setUpdateTime(new Date());
    LambdaUpdateWrapper<DtsTopic> wrapper = new LambdaUpdateWrapper<>();
    wrapper.eq(true, DtsTopic::getId, topic.getId());
    this.update(topic, wrapper);
    return topic;
  }

  @Override
  @Transactional
  public void deleteTopic(DtsTopic topic) {
    topic.setUpdateTime(new Date());
    topic.setDeleted(true);
    LambdaUpdateWrapper<DtsTopic> wrapper = new LambdaUpdateWrapper<>();
    wrapper.eq(true, DtsTopic::getId, topic.getId());
    this.update(topic, wrapper);
  }
}